<script setup lang="ts">
import { ref } from "vue";
import { useUserStore } from "@/stores/user";
const userStore = useUserStore();
import { useUserAPI } from "@/services/user";
import { ElMessage } from "element-plus";
const userAPI = useUserAPI();
import { useRouter } from "vue-router";
const router = useRouter();

const visible = defineModel("visible");

const formData = ref({
  username: "",
  password: "",
});

const handleSubmit = async () => {
  const { username, password } = formData.value;
  try {
    const result = await userAPI.postLoginByPsw(username, password);
    if (result.code === 200) {
      visible.value = false;
      formData.value = { username: "", password: "" };
      userStore.setToken(result.data.token);
      userStore.setUserInfo(result.data.user);
      ElMessage.success("登录成功");
      router.push("/discover"); // 添加这行：登录成功后跳转到发现页面
      return;
    }
    ElMessage.error(result.msg || "登录失败");
  } catch (error) {
    ElMessage.error("登录失败，请重试");
  }
};
</script>

<template>
  <el-dialog
    v-model="visible"
    width="400px"
    class="login-dialog"
    align-center
    destroy-on-close
  >
    <template #header>
      <div class="text-2xl font-semibold px-6">登录</div>
    </template>
    <el-form :model="formData" label-position="top" class="px-6">
      <el-form-item label="用户名">
        <el-input
          v-model="formData.username"
          size="large"
          placeholder="请输入用户名"
        />
      </el-form-item>
      <el-form-item label="密码">
        <el-input
          v-model="formData.password"
          type="password"
          size="large"
          placeholder="请输入密码"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="flex justify-start gap-2 px-6 pb-4">
        <el-button type="primary" size="large" @click="handleSubmit">
          <span class="text-sm py-2">芝麻开门！</span>
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped></style>
